<template>
  <div>
    <!-- 商品相关操作-->
    <div>
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="商品编号">
          <el-input v-model="searchParam.productId" placeholder="商品编号"></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchParam.productName" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchParam.productCategoryId" placeholder="请选择">
            <el-option
                v-for="item in productCategoryList"
                :key="item.productCategoryId"
                :label="item.productCategoryName"
                :value="item.productCategoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="searchParam.productStatus" placeholder="请选择">
            <el-option label="在售" value="在售"></el-option>
            <el-option label="2" value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- 查询按钮 -->
        <el-form-item>
          <el-button @click="search">查询</el-button>
        </el-form-item>
        <!-- 清空查询按钮-->
        <el-form-item>
          <el-button @click="clearSearchParam">重置</el-button>
        </el-form-item>
        <!-- 添加商品按钮 -->
        <el-form-item>
          <el-button round @click="addProductDialog">添加商品</el-button>
        </el-form-item>
        <!-- 批量删除按钮 -->
        <el-form-item>
          <el-button round @click="deleteBatch">批量删除</el-button>
        </el-form-item>
        <!-- 导出报表按钮 -->
        <el-form-item>
          <el-button round @click="expReport">导出报表</el-button>
        </el-form-item>
        <!-- 导入报表按钮-->
        <el-form-item>
          <el-upload :action="`http://localhost:8081/api/product/impReport?token=${token}`"
                     :show-file-list="false"
                     :on-success="successImpReport">
            <el-button round size="small">导入报表</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <!-- 商品展示 -->
    <div>
      <el-table :data="productList" @selection-change="handleSelectionChange" ref="table" :row-key="getRowKeys"
                style="width: 100%">
        <!-- 多选列 -->
        <el-table-column type="selection" align="center" width="50" :reserve-selection="true"></el-table-column>
        <!-- 第一列 -->
        <el-table-column align="center" width="85" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="alterProductDialog(scope.row)">编辑</el-button>
            <el-button type="text" size="small" style="color: #ff5555" @click="deleteProduct(scope.row.productId)">删除
            </el-button>
          </template>
        </el-table-column>
        <!-- 其他列 -->
        <el-table-column prop="productId" align="center" width="70" label="商品编号"></el-table-column>
        <el-table-column align="center" width="70" label="商品图片">
          <template v-slot="scope">
            <el-image
                style="width: 25px;height: 40px;"
                :src="'http://localhost:8081/api/files/download/'+scope.row.productImage"
                :preview-src-list="['http://localhost:8081/api/files/download/'+scope.row.productImage]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productName" align="center" width="80" label="商品名称"></el-table-column>
        <el-table-column prop="productPrice" align="center" width="80" label="商品售价"></el-table-column>
        <el-table-column prop="productStatus" align="center" width="80" label="商品状态"></el-table-column>
        <el-table-column prop="productQuantity" align="center" width="80" label="商品库存"></el-table-column>
        <el-table-column prop="productCategoryName" align="center" width="80" label="商品分类"></el-table-column>
        <el-table-column prop="productDescription" align="center" width="300" label="商品描述"></el-table-column>
        <el-table-column prop="createdTime" align="center" label="创建时间"></el-table-column>
        <el-table-column prop="updatedTime" align="center" label="更新时间"></el-table-column>
      </el-table>
    </div>
    <!-- 分页栏目 -->
    <div>
      <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          :current-page="searchParam.pageNum"
          :page-size="searchParam.pageSize"
          :page-sizes="[5, 10, 20, 40, 80, 160]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <!-- 商品对话框 -->
    <div>
      <el-dialog title="商品信息" :visible.sync="productDialog.visible" width="30%">
        <el-form :model="productDialog.form">
          <el-form-item label="商品名称：" label-width="20%">
            <el-input v-model="productDialog.form.productName" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="商品描述：" label-width="20%">
            <el-input v-model="productDialog.form.productDescription" autocomplete="off"
                      style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="商品售价：" label-width="20%">
            <el-input v-model="productDialog.form.productPrice" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="商品状态：" label-width="20%">
            <el-input v-model="productDialog.form.productStatus" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="商品库存：" label-width="20%">
            <el-input v-model="productDialog.form.productQuantity" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="商品分类：" label-width="20%">
            <el-select v-model="productDialog.form.productCategoryId" placeholder="请选择">
              <el-option
                  v-for="item in productCategoryList"
                  :key="item.productCategoryId"
                  :label="item.productCategoryName"
                  :value="item.productCategoryId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品图片：" label-width="20%">
            <el-upload action="http://localhost:8081/api/files/upload" :on-success="successUploadImage">
              <el-button size="small" type="primary">点击上传</el-button>
              <span slot="tip" style="margin-left: 15px">只能上传 jpg/png 文件,且不超过500k</span>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="productDialog.visible = false;clearProductDialogFrom()">取 消</el-button>
          <el-button type="primary" @click="addProduct" v-if="productDialog.showAddProductButton">确 认</el-button>
          <el-button type="primary" @click="alterProduct" v-if="productDialog.showAlertProductButton">确 认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import axiosUtil from "@/utils/axiosUtil";

export default {
  name: 'listView',
  data() {
    return {
      /* 商品相关操作 */
      // 分页参数
      searchParam: {
        productId: null,
        productName: null,
        productCategoryId: null,
        productStatus: null,
        pageNum: 1,
        pageSize: 5
      },
      productCategoryList: [],
      /* 商品展示*/
      // 商品列表
      productList: [],
      /* 分页栏目 */
      // 商品总数
      total: 0,
      /* 商品对话框*/
      // 商品对话框
      productDialog: {
        // 对话框是否显示，false：隐藏
        visible: false,
        // 商品信息
        form: {
          productName: null,
          productCategoryId: null,
          productStatus: null,
          productImage: null,
          productDescription: null,
          productQuantity: null,
          productPrice: null,
        },
        // 商品按钮展示
        showAddProductButton: false,
        showAlertProductButton: false
      },
      /* 其他 */
      // 多选行
      selectedRow: [],
      // 令牌
      token: null,
    };
  },
  methods: {
    /* 页面准备方法 */
    // 缓存所有商品分类
    findProductCategory() {
      axiosUtil.get("/productCategory").then(res => {
        if (res["code"] === '1') {
          this.productCategoryList = res.data;
        }
      })
    },
    /* 商品相关操作 */
    // 查询商品
    search() {
      axiosUtil.get("/product/search", {params: this.searchParam}).then(res => {
        if (res.code === '1') {
          this.productList = res.data.list;
          this.total = res.data.total;
        }
      })
    },
    // 重置查询
    clearSearchParam() {
      this.searchParam.productId = null;
      this.searchParam.productName = null;
      this.searchParam.productCategoryId = null;
      this.searchParam.productStatus = null;
      this.searchParam.pageNum = 1;
      this.searchParam.pageSize = 5;
      this.search(this.searchParam);
    },
    // 添加商品对话框
    addProductDialog() {
      this.clearProductDialogFrom();
      this.productDialog.showAddProductButton = true;
      this.productDialog.showAlertProductButton = false;
      // 打开对话框
      this.productDialog.visible = true;
    },
    // 批量删除
    deleteBatch() {
      this.$confirm('此操作将永久删除选择商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.selectedRow.length === 0) {
          this.$message.warning('你未勾选要删除的商品')
          return
        }
        axiosUtil.post("/product/deleteBatch", this.selectedRow).then(res => {
          if (res['code'] === "1") {
            // 刷新商品
            this.search();
            this.$message.success('删除成功!');
          } else {
            this.$message.error(res['msg'])
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 导出报表
    expReport() {
      location.href = "http://localhost:8081/api/product/expReport?token=" + this.token;
    },
    // 导入报表成功钩子
    successImpReport(res) {
      if (res['code'] === "1") {
        this.$message.success("批量导入成功");
        this.search();
      } else {
        this.$message.error("批量导入出错");
      }
    },
    /* 商品展示 */
    // 批量选中商品
    handleSelectionChange(val) {
      // console.info('选中的商品：', this.selectedRow)
      this.selectedRow = val;
    },
    getRowKeys(row) {
      return row.productId;
    },
    // 修改商品对话框
    alterProductDialog(obj) {
      this.productDialog.form = obj;
      this.productDialog.showAddProductButton = false;
      this.productDialog.showAlertProductButton = true;
      // 打开对话框
      this.productDialog.visible = true
      // 刷新商品
      this.search();
    },
    // 删除商品
    deleteProduct(productId) {
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axiosUtil.delete(`/product/delete/${productId}`).then(res => {
          if (res['code'] === "1") {
            // 刷新商品
            this.search();
            this.$message.success('删除成功!');
          } else {
            this.$message.error(res['msg'])
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      });
    },
    /* 分类栏目 */
    // 分页查询
    pageSizeChange(pageSize) {
      this.searchParam.pageSize = pageSize;
      this.search(this.searchParam);
    },
    pageNumChange(pageNum) {
      this.searchParam.pageNum = pageNum;
      this.search(this.searchParam);
    },
    /* 商品对话框 */
    // 清空添加表单
    clearProductDialogFrom() {
      this.productDialog.form = {
        productName: null,
        productCategoryId: null,
        productStatus: null,
        productImage: null,
        productDescription: null,
        productQuantity: null,
        productPrice: null,
      }
    },
    // 图片文件上传成功钩子
    successUploadImage(res) {
      this.productDialog.form.productImage = res.data;
    },
    // 添加商品
    addProduct() {
      axiosUtil.post("/product/add", this.productDialog.form).then(res => {
        if (res["code"] === '1') {
          // 刷新商品
          this.search();
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }
      })
      // 清空表单方便下次输入
      this.clearProductDialogFrom()
      // 关闭对话框
      this.productDialog.visible = false
    },
    // 修改商品
    alterProduct() {
      axiosUtil.post("/product/alter", this.productDialog.form).then(res => {
        if (res.code === '1') {
          // 刷新商品
          this.search();
          this.$message.success("操作成功")
        } else {
          this.$message.error(res['msg'])
        }
      })
      // 清空表单方便下次输入
      this.clearProductDialogFrom()
      // 关闭对话框
      this.productDialog.visible = false
    },
  },
  mounted() {
    // 页面加载时保存 token
    let user = localStorage.getItem("user");
    this.token = JSON.parse(user).token;
    // console.log(this.token)
  },
  created() {
    this.search();
    this.findProductCategory();
  },
}
</script>

<style>

</style>
